<template>
  <div class="login-container">
    <el-card class="login-card">
      <div class="login-header">
        <h1 class="title">汽车租赁管理系统</h1>
      </div>
      <!-- 登录表单 -->
      <el-form
        v-if="!isRegister"
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名(账号)"
            :prefix-icon="User"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            :prefix-icon="Lock"
            show-password
            @keyup.enter="handleLogin"
          />
        </el-form-item>
        <el-form-item prop="code">
          <div class="captcha-container">
            <el-input
              v-model="loginForm.code"
              placeholder="请输入验证码"
              :prefix-icon="Key"
              class="captcha-input"
            />
            <img :src="captchaImage" @click="getCaptcha" class="captcha-image" :class="{ 'captcha-disabled': captchaCooldown }" :style="captchaCooldown ? 'pointer-events: none; filter: grayscale(1);' : ''" alt="Captcha" />
          </div>
        </el-form-item>
        <el-form-item prop="role">
          <el-radio-group v-model="loginForm.role">
            <el-radio label="admin">管理员</el-radio>
            <el-radio label="employee">员工</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            class="login-button"
            :loading="loading"
            @click="handleLogin"
          >
            登录
          </el-button>
        </el-form-item>
        <div class="form-footer">
          <el-link type="primary" @click="isRegister = true">没有账号？立即注册</el-link>
        </div>
      </el-form>

      <!-- 注册表单 -->
      <el-form
        v-else
        ref="registerFormRef"
        :model="registerForm"
        :rules="registerRules"
        class="login-form"
      >
        <el-form-item prop="username">
          <el-input
            v-model="registerForm.username"
            placeholder="请输入用户名"
            :prefix-icon="User"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码"
            :prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请确认密码"
            :prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        <el-form-item prop="name">
          <el-input
            v-model="registerForm.name"
            placeholder="请输入姓名"
            :prefix-icon="User"
          />
        </el-form-item>
        <el-form-item prop="phone">
          <el-input
            v-model="registerForm.phone"
            placeholder="请输入手机号"
            :prefix-icon="Phone"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            class="login-button"
            :loading="loading"
            @click="handleRegister"
          >
            注册
          </el-button>
        </el-form-item>
        <div class="form-footer">
          <el-link type="primary" @click="isRegister = false">已有账号？立即登录</el-link>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, Phone, Key } from '@element-plus/icons-vue'
import { login } from '@/api/auth'
import { useUserStore } from '@/stores/user'

const BASE_URL = 'http://localhost:8080'
const router = useRouter()
const userStore = useUserStore()
const loginFormRef = ref(null)
const registerFormRef = ref(null)
const loading = ref(false)
const isRegister = ref(false)
const captchaImage = ref('')
const captchaUuid = ref('')
const captchaCooldown = ref(false)
let lastCaptchaUrl = ''

// 登录表单
const loginForm = reactive({
  username: '',
  password: '',
  code: '',
  role: 'admin' // 默认管理员
})

// 注册表单
const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  name: '',
  phone: ''
})

// 登录表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
}

// 注册表单验证规则
const validateConfirmPassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== registerForm.password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

// 获取验证码
const getCaptcha = async () => {
  if (captchaCooldown.value) return
  captchaCooldown.value = true
  try {
    const response = await fetch(`${BASE_URL}/login/captcha?_t=${new Date().getTime()}`)
    if (!response.ok) {
      throw new Error('获取验证码失败')
    }
    // 撤销旧的图片URL，避免内存泄漏和缓存
    if (lastCaptchaUrl) {
      URL.revokeObjectURL(lastCaptchaUrl)
    }
    const imageBlob = await response.blob()
    const newUrl = URL.createObjectURL(imageBlob)
    captchaImage.value = newUrl
    lastCaptchaUrl = newUrl
    captchaUuid.value = response.headers.get('UUID')
    console.log('Extracted UUID:', captchaUuid.value);
  } catch (error) {
    ElMessage.error(error.message || '获取验证码失败')
  } finally {
    setTimeout(() => {
      captchaCooldown.value = false
    }, 2000) // 冷却2秒
  }
}

onMounted(() => {
  getCaptcha()
})

// 处理登录
const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  try {
    await loginFormRef.value.validate()
    loading.value = true
    
    // 根据身份选择接口
    let url = ''
    if (loginForm.role === 'admin') {
      url = '/login/admin'
    } else {
      url = '/login/employee'
    }

    // 这里login方法只传路径部分
    const response = await login(
      loginForm.username,
      loginForm.password,
      loginForm.code,
      captchaUuid.value,
      url // 只传路径
    )
    console.log('登录响应:', response)
    
    if (response.code === 200 && response.data?.token) {
      localStorage.setItem('Token', response.data.token)
      localStorage.setItem('userRole', loginForm.role) // 确保存储角色
      localStorage.setItem('user', JSON.stringify(response.data))

      // 更新用户store
      userStore.updateUserInfo({
        username: response.data.username || loginForm.username,
        name: response.data.name || response.data.username,
        ...response.data
      })

      // 添加调试信息
      console.log('登录成功，存储的角色:', loginForm.role)
      console.log('存储的用户数据:', response.data)
      console.log('localStorage中的userRole:', localStorage.getItem('userRole'))

      ElMessage.success('登录成功')
      if (loginForm.role === 'employee') {
        console.log('员工登录，跳转到 /employee')
        await router.push('/employee')
      } else {
        console.log('管理员登录，跳转到 /')
        await router.push('/')
      }
    } else {
      console.log('登录失败，页面不会跳转或刷新')
      ElMessage.error({ message: response.message || '登录失败', duration: 5000 })
    }
  } catch (error) {
    console.error('登录错误:', error)
    // 先打印后端返回内容，方便调试
    console.log('后端返回内容:', error?.response?.data)
    let msg = '登录失败，请检查网络连接'
    if (error?.response?.data) {
      if (typeof error.response.data === 'string') {
        msg = error.response.data
      } else if (error.response.data.message) {
        msg = error.response.data.message
      } else {
        msg = JSON.stringify(error.response.data)
      }
    } else if (error.message) {
      msg = error.message
    }
    ElMessage.error({ message: msg, duration: 5000 })
    setTimeout(() => { getCaptcha() }, 3000)
  } finally {
    loading.value = false
  }
}

// 处理注册
const handleRegister = async () => {
  if (!registerFormRef.value) return
  
  try {
    await registerFormRef.value.validate()
    loading.value = true
    
    const response = await fetch(`${BASE_URL}/login/register`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        username: registerForm.username,
        password: registerForm.password,
        name: registerForm.name,
        phone: registerForm.phone
      })
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const result = await response.json()
    if (result.code === 200) {
      ElMessage.success('注册成功，请登录')
      // 清空注册表单
      registerFormRef.value.resetFields()
      // 切换到登录表单
      isRegister.value = false
    } else {
      throw new Error(result.message || '注册失败')
    }
  } catch (error) {
    console.error('注册失败：', error)
    ElMessage.error(error.message || '注册失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f0f2f5;
}

.login-card {
  width: 400px;
  padding: 20px;
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.title {
  font-size: 24px;
  color: #303133;
  margin: 0;
}

.login-form {
  margin-top: 20px;
}

.login-button {
  width: 100%;
}

.form-footer {
  text-align: center;
  margin-top: 15px;
}

.captcha-container {
  display: flex;
  align-items: center;
  width: 100%;
}

.captcha-input {
  flex: 1;
  margin-right: 10px;
}

.captcha-image {
  width: 120px;
  height: 40px;
  cursor: pointer;
  border-radius: 4px;
}

.captcha-disabled { filter: grayscale(1); cursor: not-allowed; }
</style> 
